<?php

session_start();

// Include i file necessari
include('inc/config.inc.php');
include('inc/template.inc.php');
include('inc/db.inc.php');
include('inc/check.inc.php');

function preview($txt)
{ 
	$pre = $txt;
	$pre = str_replace("<br />", " ", $pre);
	$pre = str_replace("<hr>", " ", $pre);
	$pre = strip_tags($pre);
	$pre = html_entity_decode($pre);
	$preold = $pre;
	if (strlen($pre) > 0)
	{
		$pre = substr($pre, 0, 45);
		if ($pre != $preold)
			$pre .= "...";
	}
	
	return htmlentities($pre);
}

// Variabili
$user_id	= $_SESSION['uid'];
$user_name	= $_SESSION['unm'];
$msg_box 	= '';
$form 		= '';
$action		= ( ! empty($_GET['act'])) ? trim(mysql_real_escape_string($_GET['act'])) : 0;
$msglist	= '';
$dest_name	= ( ! empty($_GET['writenew'])) ? trim(mysql_real_escape_string($_GET['writenew'])) : '';
$js_script	= '';


switch($action)
{
	// Azione per l'invio di messaggi
	case 1:
				
		if( ! empty($_POST['text']) AND ! empty($_POST['user'])) 
		{
			$to = trim(mysqli_real_escape_string($db, $_POST['user']));

			if($r1 = $db -> query("SELECT user_id FROM users WHERE user_name = '$to'"))
			{
				$rd1 = $r1 -> fetch_assoc();
				$toid = $rd1['user_id'];
				$msg = trim(mysqli_real_escape_string($db, $_POST['text']));

				$db -> query("INSERT INTO mail (mail_id, mail_from, mail_to, mail_date, mail_read, mail_text) VALUES(NULL, '$user_id', '$toid',  NOW(), '0', '$msg')");
				
				$form = '';
				
				$msg_box .= '<div class="alert alert-success">';
				$msg_box .= 'Messaggio inviato con successo.';
				$msg_box .= '</div>';
			}

		}
	break;
	// Visualizzazione messaggi
	case 2:
		$msg_id = $_GET['id'];
		
		// Recupera l'elenco dei messaggi
		if($r2 = $db -> query("SELECT * FROM mail WHERE mail_id = '$msg_id'"))
		{
			$rd2 = $r2 -> fetch_assoc();
			
			// Variabili
			$dest	= $rd2['mail_to'];
			$dest	= ucfirst($dest);
			$mid	= $rd2['mail_id'];
			$mitt	= $rd2['mail_from'];
			
			if($r3 = $db -> query("SELECT user_name FROM users WHERE user_id = '$mitt'"))
			{
				$rd3 = $r3 -> fetch_assoc();
				
				// Nome personaggio
				$user_name = trim(htmlentities($rd3['user_name']));
				if($dest == $user_id)
				{
					// Contenuto del messaggio
					$msgcontent = trim(htmlentities(bbtext($rd2['mail_text']))) . '<br />';
					
					// Info del messaggio
					$msginfo = '<a href="avatar.php?id=' . $mitt . '" target="_self"><b>' . $user_name . '</b></a>';
					$msginfo .= ' - <i>' . date('d/m/Y', strtotime($rd2['mail_date'])) . '</i>';
					
					// Stampa il messaggio
					$form .= '<div class="panel panel-default" id="mini-chat">';
					$form .= '<div class="panel-heading">' . $msginfo . '</div>';
					$form .= '<div class="panel-body">' . $msgcontent . '</div>';
					$form .= '<div class="panel-footer"> <a href="mail.php?act=3&id=' . $mitt . '" class="btn btn-default" target="_self">Rispondi</a>';
					$form .= ' <a href="mail.php?act=4&id=' . $msg_id . '" class="btn btn-danger" target="_self">Cancella</a></div></div><hr />';
					
					// Imposta il messaggio come gi� letto					
					$db -> query("UPDATE mail SET mail_read = '1' WHERE mail_id = '$msg_id'");
					
					$r2 -> close();
				} else {
					
					$msg_box .= '<div class="box_danger">';
					$msg_box .= 'Destinatario non riconosciuto.';
					$msg_box .= '</div>';
					
				}
			}
		}
	break;
	// Risposta a messaggi
	case 3:
		if($dest_name == '')
		{
			$mitt_id = $_GET['id'];
			
			if($r4 = $db -> query("SELECT user_name FROM users WHERE user_id = '$mitt_id'"))
			{
				$rd4 = $r4 -> fetch_assoc();
				
				$dest_name = trim(htmlentities($rd4['user_name']));
				
			}
		} else {
			$js_script .= "<script>$(function () { $('#messageModal').modal('show'); });</script>";
		}
	break;
	// Cancellazione messaggi
	case 4: 
		$msg_id = $_GET['id'];
		$db -> query("DELETE FROM mail WHERE mail_id = '$msg_id'");
		
		$msg_box .= '<div class="alert alert-success">';
		$msg_box .= 'Messaggio eliminato con successo.';
		$msg_box .= '</div>';
	break;
}

// Recupera l'elenco dei messaggi
if($r5 = $db -> query("SELECT * FROM mail WHERE mail_to = '$user_id' ORDER BY mail_read, mail_date DESC"))
{
	while($rd5 = $r5 -> fetch_assoc())
	{
		$from	= trim(htmlentities($rd5['mail_from']));
		$mid	= $rd5['mail_id'];
		
		if($r6 = $db -> query("SELECT user_name, user_id FROM users WHERE user_id = '$from'"))
		{
			$rd6 = $r6 -> fetch_assoc();
		}

		$msglist .= '<tr><td><a href="avatar.php?id=' . $rd6['user_id'] . '" target="_self">' . trim(htmlentities(ucfirst($rd6['user_name']))) . '</a></td>';
		$msglist .= '<td>' . date('d/m/Y H:i', strtotime($rd5['mail_date'])) . '</td>';
		$msglist .= '<td><a href="mail.php?act=2&id=' . $mid . '" target="_self">' . preview($rd5['mail_text']) . '</a></rd></tr>';
	}
	
	$r5 -> close();
}

// Lista delle tag speciali
$tags = array(
				'temp_title' => $g_name, 'temp_msglist' => $msglist, 'temp_msgbox' => $msg_box, 
				'temp_form' => $form, 'temp_dest' => $dest_name, 'temp_jscript' => $js_script
			);

// Carica il template e formatta le tag speciali
$temp = new template('style/mail.template.html');
$temp -> replace($tags);

// Visualizza l'output
echo $temp -> show();

// Chiude la connessione al database
$db -> close();

?>